package org.zoomdev.zoom.common.caster;

import org.zoomdev.zoom.aop.Constructor;
import org.zoomdev.zoom.aop.factory.ConstructorFactory;
import org.zoomdev.zoom.aop.factory.SetterFactory;
import org.zoomdev.zoom.common.utils.Classes;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 只对json序列化的Map做优化
 * 注意： 只针对简单类型或者简单类型的复合类型
 */
public class FastMap2BeanCaster implements ValueCaster {
    private final Constructor constructor;
    private final Map<String, ToValueFastCaster> fieldMap;

    public FastMap2BeanCaster(Class<?> type) {
        this.fieldMap = new HashMap<>();
        constructor = ConstructorFactory.FACTORY.create(type);
        List<Field> fields = Classes.getFields(type);
        ToValueFastCaster[] ret = new ToValueFastCaster[fields.size()];
        for (int i = 0, c = fields.size(); i < c; ++i) {
            Field f = fields.get(i);
            ToValueFastCaster field = new ToValueFastCaster(
                    SetterFactory.FACTORY.create(f),
                    FastToBeanCaster.getCaster(f.getGenericType()),
                    f.getName());
            ret[i] = field;
            fieldMap.put(f.getName(), field);
        }

    }

    @Override
    public Object to(Object src) {
        if (src == null) {
            return null;
        }
        Map<String, Object> map = (Map<String, Object>) src;
        Object instance = constructor.newInstance();
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            String key = entry.getKey().toString();
            ToValueFastCaster field = fieldMap.get(key);
            if (field != null) {
                field.set(instance, entry.getValue());
            }
        }
        return instance;
    }
}
